import React, { useState, useRef ,useEffect  } from 'react';
import { history } from 'umi';
import { Space, message, Card, Modal,Tabs, Descriptions, Divider,Button,Select,Collapse } from 'antd';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { getDeviceInfo ,queryDeviceHistoryList} from '@/services/device';
const { Option } = Select;
const { confirm } = Modal;
import { ExclamationCircleOutlined,PlusOutlined } from '@ant-design/icons';
const { Panel } = Collapse;
import { queryDeviceTypeList} from '@/services/devicetype';
import styles from './index.less';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { querySpecificDeviceAttr,removeDeviceSpecificAttr,updateDeviceSpecificAttr, addSpecificDeviceAttr, querySpecialDeviceAttr } from '@/services/deviceattr';
const { TabPane } = Tabs;
import moment from 'moment';
const DeviceDetail: React.FC = (props: any) => {
const { params } = props.match;

const [deviceInfo, setDeviceInfo] = useState<API.DeviceItem>({});
const [deviceAttrs, setDeviceAttrs] = useState<API.SysDeviceAttrItem[]>();
const [xwidth, setXwidth] = useState(1000);
const setSelectData = async () => {
  var info=await  getDeviceInfo(params);
   await changeAttr(info);
   if(info.deviceTypeId==3&&xwidth!=3500){
    setXwidth(3500)
   }
  
  info.protocol= info.protocolConfig==null||info.protocolConfig==""?null:JSON.parse(info.protocolConfig);

  setDeviceInfo(info);
};

const changeAttr = async (info:API.DeviceItem) => {
  var attr= await querySpecialDeviceAttr({deviceId:info.deviceId,deviceTypeId:info.deviceTypeId});
  setDeviceAttrs(attr);
 
};


useEffect(() => {
  setSelectData();

}, []);


//删除单个
const toremove = async (fields: any) => {
  try {
    await removeDeviceSpecificAttr({attrId:fields.attrId,deviceId:fields.deviceId,deleteFlag:1});
    message.success('删除成功，正在刷新！');
    actionRef.current?.reload();
    return true;
  } catch (error) {
    message.error('删除失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */
 const updateState = async (fields: any) => {
  try {
    await updateDeviceSpecificAttr({attrId:fields.attrId,deviceId:fields.deviceId,useState:(fields.useState==0?1:0)});
    message.success('更新成功');
    actionRef.current?.reload();
    return true;
  } catch (error) {
    message.error('新失败请重试！');
    return false;
  }
};

/**
 * 添加节点
 * @param fields
 */
 const handleAdd = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在添加');
  try {

    await addSpecificDeviceAttr({...fields,deviceTypeId:deviceInfo.deviceTypeId,deviceId:deviceInfo.deviceId});
    hide();
    resetForm();
    changeAttr(deviceInfo);
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};


// /**
//  * 更新节点
//  * @param fields
//  */
//  const handleUpdate = async (fields: any) => {
//   const hide = message.loading('正在保存');
//   try {
//     await updateDeviceAttr(fields);
//     hide();

//     message.success('保存成功');
//     return true;
//   } catch (error) {
//     hide();
//     message.error('保存失败请重试！');
//     return false;
//   }
// };


const remove = async (fields: any) => {



  confirm({
    title: '您确定要删除吗?',
    icon: <ExclamationCircleOutlined />,
    async onOk() {
      await toremove(fields);
      actionRef.current?.reload();
    },
    onCancel() {
      console.log('Cancel');
    },
  });
 
};
const actionRef = useRef<ActionType>();
const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [formValues, setFormValues] = useState({});


  const columns: ProColumns[] = [

    {
      title: '序号',
      search: false,
      dataIndex: 'deviceAttr',
       render: (attr) => (
        <Space >
           {attr.orderNo}
        </Space>
      ),
    },

    {
      title: '变量名称',
      search: false,
      dataIndex: 'deviceAttr',
      render: (attr) => (
       <Space >
          {attr.dispalyName}
       </Space>
     )
    },
    {
      title: '页面展示名称',
      dataIndex: 'deviceAttr',
      render: (attr) => (
       <Space >
          {attr.browseName}
       </Space>
     )
    },
    {
      title: '单位',
      search: false,
      dataIndex: 'deviceAttr',
      render: (attr) => (
       <Space >
          {attr.unit}
       </Space>
     )
    },
    {
      title: '数据类型',
      search: false,
      dataIndex: 'deviceAttr',
      render: (attr) => (
       <Space >
          {attr.dataType}
       </Space>
     )
    },
    {
      title: '最大值',
      search: false,
      dataIndex: 'deviceAttr',
      render: (attr) => (
       <Space >
          {attr.maxValue}
       </Space>
     )
    },
    {
      title: '最小值',
      search: false,
      dataIndex: 'deviceAttr',
      render: (attr) => (
       <Space >
          {attr.minValue}
       </Space>
     )
    },
    {
      title: '是否启用',
      dataIndex: 'useState',
      valueType: 'radio',
      valueEnum: {
        1: { text: '启用'},
        0: { text: '未启用'},
      }
    },
    // {
    //   title: '创建时间',
    //   search: false,
    //   dataIndex: 'createTime',
    // },
    // {
    //   title: '更新时间',
    //   search: false,
    //   dataIndex: 'updateTime',

    // },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>
          {/* <a
          key="editable"
          onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >
          编辑
        </a>
        <Divider type="vertical" /> */}
        <a
        key="updateState"
        onClick={async () => {    await updateState( record)}} >
        {record.useState==0?'启用':'禁用'} 
        </a>
        <Divider type="vertical" />
        <a onClick={async () => { await remove(record);   }}  >删除</a>
      </>)
    },
  ];




  const columnsType3: ProColumns[] = [

    {
      title: '时间',
      dataIndex: 'time',
      valueType: 'dateRange',
      hideInTable: true,
      initialValue: [moment().add(-1, 'day'), moment()],
    },
    {
      title: '时间',
      dataIndex: 'acquisitionTime',
      search:false,
    },
    {
      title: '是否在线',
      dataIndex: 'online',
      search:false,
      valueEnum: {
        1: { text: '离线'},
        0: { text: '在线'},
      }
    },
    {
      title: 'A相电压',
      search:false,
      dataIndex: 'phaseaVoltage'
    },
    {
      title: 'B相电压',
      search:false,
      dataIndex: 'phasebVoltage'
    },
    {
      title: 'C相电压',
      search:false,
      dataIndex: 'phasecVoltage'
    },
    {
      title: '线电压Uab',
      search:false,
      dataIndex: 'uabLineVoltage'
    },
    {
      title: '线电压Ubc',
      search:false,
      dataIndex: 'ubcLineVoltage'
    },
    {
      title: '线电压Uca',
      search:false,
      dataIndex: 'ucaLineVoltage'
    },
    {
      title: 'A相电流',
      search:false,
      dataIndex: 'phaseaCurrent'
    },
    {
      title: 'B相电流',
      search:false,
      dataIndex: 'phasebCurrent'
    },
    {
      title: 'C相电流',
      search:false,
      dataIndex: 'phasecCurrent'
    },
    {
      title: '零线电流',
      search:false,
      dataIndex: 'zeroLineCurrent'
    },
    {
      title: 'A相有功功率',
      search:false,
      dataIndex: 'phaseaActivePower'
    },
    {
      title: 'B相有功功率',
      search:false,
      dataIndex: 'phasebActivePower'
    },
    {
      title: 'C相有功功率',
      search:false,
      dataIndex: 'phasecActivePower'
    },
    {
      title: '合相有功功率',
      search:false,
      dataIndex: 'activePower'
    },
    {
      title: 'A相无功功率',
      search:false,
      dataIndex: 'phaseaReactivePower'
    },
    {
      title: 'B相无功功率',
      search:false,
      dataIndex: 'phasebReactivePower'
    },
    {
      title: 'C相无功功率',
      search:false,
      dataIndex: 'phasecReactivePower'
    },
    {
      title: '合相无功功率',
      search:false,
      dataIndex: 'reactivePower'
    },
    {
      title: 'A相视在功率',
      search:false,
      dataIndex: 'phaseaApparentPower'
    },
    {
      title: 'B相视在功率',
      search:false,
      dataIndex: 'phasebApparentPower'
    },
    {
      title: 'C相视在功率',
      search:false,
      dataIndex: 'phasecApparentPower'
    },
    {
      title: '合相视在功率',
      search:false,
      dataIndex: 'apparentPower'
    },
    {
      title: 'A相功率因数',
      search:false,
      dataIndex: 'phaseaPowerFactor'
    },
    {
      title: 'B相功率因数',
      search:false,
      dataIndex: 'phasebPowerFactor'
    },
    {
      title: 'C相功率因数',
      search:false,
      dataIndex: 'phasecPowerFactor'
    },
    {
      title: '合相功率因数',
      search:false,
      dataIndex: 'powerFactor'
    },
    {
      title: '频率',
      search:false,
      dataIndex: 'gridFrequency'
    },

  
    {
      title: '有功总电能',
      search:false,
      dataIndex: 'totalActiveEnergy'
    },
    {
      title: '有功费率1电能',
      search:false,
      dataIndex: 'totalActiveEnergy1'
    },
    {
      title: '有功费率2电能',
      search:false,
      dataIndex: 'totalActiveEnergy2'
    },
    {
      title: '有功费率3电能',
      search:false,
      dataIndex: 'totalActiveEnergy3'
    },
    {
      title: '有功费率4电能',
      search:false,
      dataIndex: 'totalActiveEnergy4'
    },

    {
      title: '正向有功总电能',
      search:false,
      dataIndex: 'positiveActiveEnergy'
    },
    {
      title: '正向有功费率1电能',
      search:false,
      dataIndex: 'positiveActiveEnergy1'
    },
    {
      title: '正向有功费率2电能',
      search:false,
      dataIndex: 'positiveActiveEnergy2'
    },
    {
      title: '正向有功费率3电能',
      search:false,
      dataIndex: 'positiveActiveEnergy3'
    },
    {
      title: '正向有功费率4电能',
      search:false,
      dataIndex: 'positiveActiveEnergy4'
    },

    {
      title: '反向有功总电能',
      search:false,
      dataIndex: 'negativeActiveEnergy'
    },
    {
      title: '反向有功费率1电能',
      search:false,
      dataIndex: 'negativeActiveEnergy1'
    },
    {
      title: '反向有功费率2电能',
      search:false,
      dataIndex: 'negativeActiveEnergy2'
    },
    {
      title: '反向有功费率3电能',
      search:false,
      dataIndex: 'negativeActiveEnergy3'
    },
    {
      title: '反向有功费率4电能',
      search:false,
      dataIndex: 'negativeActiveEnergy4'
    },

    {
      title: '无功1总电能',
      search:false,
      dataIndex: 'reactiveEnergy'
    },
    {
      title: '无功1费率1电能',
      search:false,
      dataIndex: 'reactiveEnergy1'
    },
    {
      title: '无功1费率2电能',
      search:false,
      dataIndex: 'reactiveEnergy2'
    },
    {
      title: '无功1费率3电能',
      search:false,
      dataIndex: 'reactiveEnergy3'
    },
    {
      title: '无功1费率4电能',
      search:false,
      dataIndex: 'reactiveEnergy4'
    },
  ];

  const columnsType1: ProColumns[] = [

    {
      title: '时间',
      dataIndex: 'time',
      valueType: 'dateRange',
      hideInTable: true,
      initialValue: [moment().add(-1, 'day'), moment()],
    },
    {
      title: '时间',
      dataIndex: 'acquisitionTime',
      search:false,
    },
    // {
    //   title: '是否在线',
    //   dataIndex: 'online',
    //   search:false,
    //   valueEnum: {
    //     1: { text: '离线'},
    //     0: { text: '在线'},
    //   }
    // },
    {
      title: '运行频率',
      search:false,
      dataIndex: 'operatingFrequency'
    },
    {
      title: '设定频率',
      search:false,
      dataIndex: 'setFrequency'
    },
    {
      title: '母线电压',
      search:false,
      dataIndex: 'busVoltage'
    },
    {
      title: '输出电压',
      search:false,
      dataIndex: 'outputVoltage'
    },
    {
      title: '输出电流',
      search:false,
      dataIndex: 'outputCurrent'
    },
    {
      title: '运行转速',
      search:false,
      dataIndex: 'rotationalVelocity'
    },
    {
      title: '输出功率',
      search:false,
      dataIndex: 'outputPower'
    },
    {
      title: '输出转矩',
      search:false,
      dataIndex: 'outputTorque'
    }
  ];


  const columnsType2: ProColumns[] = [

    {
      title: '时间',
      dataIndex: 'time',
      valueType: 'dateRange',
      hideInTable: true,
      initialValue: [moment().add(-1, 'day'), moment()],
    },
    {
      title: '时间',
      dataIndex: 'acquisitionTime',
      search:false,
    },
    {
      title: '是否在线',
      dataIndex: 'online',
      valueEnum: {
        1: { text: '离线'},
        0: { text: '在线'},
      },
      search:false
    },
    {
      title: 'A相电流',
      search:false,
      dataIndex: 'phaseaCurrent'
    },
    {
      title: 'B相电流',
      search:false,
      dataIndex: 'phasebCurrent'
    },
    {
      title: 'C相电流',
      search:false,
      dataIndex: 'phasecCurrent'
    },
    {
      title: '线电压Uab',
      search:false,
      dataIndex: 'uabLineVoltage'
    },
    {
      title: '线电压Ubc',
      search:false,
      dataIndex: 'ubcLineVoltage'
    },
    {
      title: '线电压Uca',
      search:false,
      dataIndex: 'ucaLineVoltage'
    }  ,
    {
      title: '有功功率',
      search:false,
      dataIndex: 'activePower'
    },
    {
      title: '无功功率',
      search:false,
      dataIndex: 'reactivePower'
    },
    {
      title: '视在功率',
      search:false,
      dataIndex: 'apparentPower'
    },
    {
      title: '功率因数',
      search:false,
      dataIndex: 'powerFactor'
    },
    {
      title: '电流不平衡率',
      search:false,
      dataIndex: 'currentUnbalance'
    },
    {
      title: '热容量百分比',
      search:false,
      dataIndex: 'heatCapacityPercentage'
    },
  ];
  return (
    <div className={styles.main}>
      <a   onClick={()=>history.goBack()}> 返回上一级  </a>
      <Card>
         <Descriptions  column={4}   title={"设备基本信息"}>
          <Descriptions.Item label="设备位号">{deviceInfo.deviceNo}</Descriptions.Item>
          <Descriptions.Item label="设备名称">{deviceInfo.deviceName}</Descriptions.Item>
          <Descriptions.Item label="设备类型">{deviceInfo.deviceTypeName}</Descriptions.Item>
          {/* <Descriptions.Item label="驱动名称">{deviceInfo.protocolTypeName}</Descriptions.Item> */}
     
          <Descriptions.Item label="所在区域">{deviceInfo.areaName}</Descriptions.Item>
          <Descriptions.Item label="所在位置">{deviceInfo.devicePosition}</Descriptions.Item>
          <Descriptions.Item label="设备描述">{deviceInfo.deviceDesc}</Descriptions.Item>
          <Descriptions.Item label="设备品牌">{deviceInfo.deviceBrand}</Descriptions.Item>
          <Descriptions.Item label="设备型号">{deviceInfo.deviceModel}</Descriptions.Item>
          <Descriptions.Item label="产品序列号">{deviceInfo.seriaNumber}</Descriptions.Item>
          <Descriptions.Item label="上线时间">{deviceInfo.onlineTime}</Descriptions.Item>
          <Descriptions.Item label="启用状态">{deviceInfo.useState==1?'启用':'未启用'}</Descriptions.Item>
          <Descriptions.Item label="最新维保时间">{deviceInfo.latestMaintenanceTime}</Descriptions.Item>
          <Descriptions.Item label="供货商">{deviceInfo.supplier}</Descriptions.Item>
          <Descriptions.Item label="供货商联系人姓名">{deviceInfo.supplierName}</Descriptions.Item>
          <Descriptions.Item label="供货商联系人电话">{deviceInfo.supplierPhone}</Descriptions.Item>
          <Descriptions.Item label="驱动名称">{deviceInfo.driverName}</Descriptions.Item>
          <Descriptions.Item label="通讯协议：">{deviceInfo.protocolTypeName}


          {deviceInfo?.protocol!=null&&deviceInfo?.protocol!=""?
             <> ( { Object.keys(deviceInfo.protocol).map((item, index) => (
             <> {item}:{deviceInfo.protocol[item]} </>
            ))}) </>:<></>}
         

           </Descriptions.Item>
        </Descriptions>
        {/* <Descriptions title={"通讯协议：  "+deviceInfo.protocolTypeName} column={4}>
          {deviceInfo.protocol?Object.keys(deviceInfo.protocol).map((item) => (
              <Descriptions.Item label={item}>{deviceInfo.protocol[item]}</Descriptions.Item>
            
            )):null}   
          </Descriptions> */}
            {/* <Collapse bordered={false} >
            <Panel header={"通讯协议：  " + deviceInfo?.protocolTypeName} key="1">
              <Descriptions column={4} key={3}>
              {deviceInfo?.protocol ? Object.keys(deviceInfo.protocol).map((item, index) => (
                <Descriptions.Item key={index} label={item}>{deviceInfo?.protocol[item]}</Descriptions.Item>
              )) : null}
              </Descriptions>
            </Panel>
            
          </Collapse> */}
       {/* <Divider  className={styles.divider} /> */}
       <div className={styles.tableBox}>
       <Tabs defaultActiveKey="1" style={{ width: '100%' }}>
          <TabPane tab="历史数据"  key={1}>
     
        {/* <div className={styles.title}>特殊变量</div> */}
        {deviceInfo.deviceTypeId!=null ? <ProTable
          style={{ marginBottom: 24 }}
          toolBarRender={(action, { selectedRows }) => [
         
         
          ]}
          headerTitle=""
         // pagination={false}
          // search={false}
          options={false}
          // toolBarRender={false}
          actionRef={actionRef}
          columns={deviceInfo.deviceTypeId==1?columnsType1:deviceInfo.deviceTypeId==2?columnsType2:columnsType3}
          // request={ async ( param) => {return  await  querySpecificDeviceAttr({ ...param })  }}
          request={(param) => queryDeviceHistoryList({...param,...params,type:deviceInfo.deviceTypeId})}
          scroll={{ x: xwidth }} 
            search={{
              //defaultCollapsed: false,
              labelWidth: 'auto',
            }}

          rowKey="acquisitionTime"
        />:null} 
   
       </TabPane>
       <TabPane tab="特殊变量"  key={2}>
     
     {/* <div className={styles.title}>特殊变量</div> */}
     <ProTable
       style={{ marginBottom: 24 }}
       toolBarRender={(action, { selectedRows }) => [
         <Button icon={<PlusOutlined />} type="primary"  className={styles.addBtn} onClick={() => handleModalVisible(true)}>
           新增
         </Button>,
      
       ]}
       headerTitle=""
      // pagination={false}
       search={false}
       options={false}
       // toolBarRender={false}
       actionRef={actionRef}
       columns={columns}
       // request={ async ( param) => {return  await  querySpecificDeviceAttr({ ...param })  }}
       request={(param) =>    querySpecificDeviceAttr({...param,...params,...{current:1,  pageSize:100}}) }
       rowKey="attrId"
     />

    </TabPane>
    </Tabs>
    </div>
      </Card>
      {deviceAttrs?
      <CreateForm
        onSubmit={async (value,resetForm) => {
       
          const success = await handleAdd(value,resetForm);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
               actionRef.current.reload();
            }
          }
        }}
        attrList={deviceAttrs}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
       
      />:null
        }
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
         
        />
      ) : null}
    </div>
  );
};

export default DeviceDetail;